/*
 * @Overview:   index
 * @Author:     Zi_Jun
 * @Email:      zijun2030@163.com
 * @Date:       2020/12/7 10:36
 * @Mark:       //
 */

import { VAxios } from './axios';
import { IAxiosRequestConfig, IAxiosResponse, ICreateAxiosOptions, IRequestOptions } from './types';
import { AxiosTransform } from './axios-transform';
import { ContentTypeEnum } from '/@/enums/http-enum';
import { deepMerge } from '/@/utils/common';
import { openLoading, closeLoading } from './loading';
import { ElMessage } from 'element-plus';
import { networkError, ERROR_CODE, showErrorMessage } from './axios-error';

const transform: AxiosTransform = {
  // 请求之前，处理请求参数
  beforeRequest: (config: IAxiosRequestConfig, options: IRequestOptions) => {
    const { isHideRequestLoading } = options;
    if (!isHideRequestLoading) {
      openLoading();
    }
    return config;
  },

  responseInterceptors: (response: IAxiosResponse) => {
    closeLoading();
    // status为200,返回数据处理
    // 以下为针对性数据处理
    const {
      data: { error_code, error_msg },
    } = response;
    if (error_code === 0) {
      return response.data;
    } else {
      ElMessage.error(error_msg);
      return Promise.reject(error_msg);
    }
  },

  responseInterceptorsCatch: (error: any) => {
    // 请求所得到的响应的状态码超出了2xx | 请求完全得不到响应
    closeLoading();
    if (error.response) {
      const { status } = error.response;
      const msg = ERROR_CODE.find((e) => e.code === status).msg || '';
      msg ? showErrorMessage(msg) : networkError(error.message);
    } else {
      networkError(error.message);
    }
    return Promise.reject(error);
  },
};

/**
 * 创建一个axios，用于封装默认值
 * @param opt {Object} 优先取值对象，包含axios配置和自定义配置,默认为undefined
 */
const createAxios = (opt?: Partial<ICreateAxiosOptions>) => {
  return new VAxios(
    deepMerge(
      {
        timeout: 15 * 1000,
        baseURL: import.meta.env.VITE_API_URL || '',
        headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
        transform,
        requestOptions: {
          isIgnoreCancelToken: false,
          isHideRequestLoading: true,
        },
      },
      opt || {},
    ),
  );
};

export const packAxios = createAxios();
